<template>
  <div class="table">
    <el-table
      :data="scoreList.slice(handleChangeIndexF, handleChangeIndexL)"
      style="width: 100%"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      border
    >

      <el-table-column prop="name" label="姓名" width="120" />

      <el-table-column prop="className" label="班级" width="200">
        <template #header>
          <el-select
            v-model="classId"
            @change="changeClass"
            filterable
            placeholder="班级"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="成绩表" width="830">
        <!-- <el-table-column prop="courseName" label="科目" width="120" />
        <el-table-column prop="num" label="成绩" width="120" /> -->
        <!-- <el-table-column prop="address" label="Address" />
        <el-table-column prop="zip" label="Zip" width="120" /> -->
        <template #default="scope">
          <!-- <div>{{ scope.name }}</div> -->
          <!-- <el-table :data="scope.row.score" style="width: 100%">
            <el-table-column prop="date" label="时间" width="150" />
             <el-table-column prop="courseName" label="科目" width="150" />
             <el-table-column prop="num" label="成绩" width="150" />
          </el-table> -->
          <div class="km_table">
            <span
              v-if="scope.row.score.length > 0"
              v-for="item in scope.row.score"
              :key="item.course_id"
            >
              <p>{{ item.courseName }}</p>
              <p>{{ item.num }}</p>
            </span>
            <span v-else>暂无数据</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="家长姓名" prop="p_name" width="150">
        <template #default="scope">
          <el-tag :type="scope.row.p_name ? '' : 'info'">{{
            scope.row.p_name ?? "未注册"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="p_phone" label="家长电话" width="180" />
      <el-table-column fixed="right" label="编辑" width="180">
        <template #default="scope">
          <el-button type="warning" size="small" @click="openDialog(scope.row,scope.$index)"
            >编辑成绩表</el-button
          >
        </template>
      </el-table-column>
    </el-table>
     <div class="demo-pagination-block" style="margin: 10px 18px">
      <!-- <div class="demonstration">All combined</div> -->
      <el-pagination
        v-model:current-page="pag.currentPage"
        v-model:page-size="pag.pageSize"
        :page-sizes="[2, 5, 10, 15, 20, 40]"
        :small="pag.small"
        :disabled="pag.disabled"
        :background="pag.background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pag.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--  -->
    <span style="display: none">{{ type }}</span>

    <!-- 对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`[${rowStudentScore.name}]成绩表`"
      width="30%"
    >
      <span>
        <el-form :model="form" label-width="80px">
          <el-form-item
            v-for="item in rowStudentScore.score"
            :key="item.id"
            :label="item.courseName"
          >
           <!-- <div style="display: flex;justify-content: space-between; align-items: center;"> -->
             <el-input v-model="item.num" :disabled="!item.type" style="width: 100%;" @keyup.enter.native="scoreUpdate(item)">
              <template #append>
                <el-button @click="scoreUpdate(item)">{{
                  item.type ? "提交" : "编辑"
                }}</el-button>
              </template>
            </el-input>
            <el-button type="danger" @click="scoredelete(item)" 
            :icon="Delete" style="margin-left:10px" circle />
           <!-- </div> -->
          </el-form-item>
          <el-form-item label="新增">
            <el-input
              v-model="newScore.num"
              placeholder="分数"
              class="input-with-select"
              @keyup.enter.native="addScore"
            >
              <template #prepend>
                <el-select
                  v-model="newScore.course_id"
                  placeholder="选择科目"
                  style="width: 115px"
                >
                  <el-option v-for="item in courseListFilter"
                  :key="item.id"
                  :label="item.name" :value="item.id" />
                 
                </el-select>
              </template>
              <template #append>
                <el-button @click="addScore">添加</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            Confirm
          </el-button>
        </span>
      </template> -->
    </el-dialog>
  </div>
</template>

<script>
import { computed, reactive, toRefs, watch } from "vue";
import { get, request } from "../../utils/http";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import { Delete } from '@element-plus/icons-vue'

export default {

  setup() {
    const store = useStore();
    let thus = reactive({
      scoreList: [],
      classId: null,
      classList: [],
      courseList:[],
      dialogVisible: false,
      rowStudentScore: {},
      rowIndex:null,
      newScore:{
        student_id:null,
        course_id:null,
        num:null,
      },
       pag: {
        currentPage: 1,
        pageSize: 10,
        small: null,
        disabled: false,
        background: false,
        total: 0,
        flag: false,
      },
    });
    let type = computed(() => {
      changeType(store.state.score.type);
      return store.state.score.type;
    });
    const changeType = (newValue) => {
      if (newValue == 0) {
        getScoreList();
      } else if (newValue == 1) {
        getScoreList({ c_id: store.state.score.nowId });
      }
    };
    const getScoreList = (data,flag = false) => {
      console.log(data);
      request.post("/score/list", { ...data }).then((res) => {
        console.log(res);
        if(flag){
          console.log(res.data);
          thus.scoreList[thus.rowIndex] = res.data[0]
          return thus.rowStudentScore = res.data[0];
        }
        thus.scoreList = res.data;
        thus.pag.total = res.data.length
      });
    };

    const getClassAndCourseList = () => {
      request.get("/class/list").then((res) => {
        thus.classList = res.data;
        thus.classList.unshift({ id: null, className: "All" });
        console.log(res);
      });
      request.get("/course/list").then(res=>{
        thus.courseList = res.data
        console.log(res,"====");
      })

    };
    const changeClass = () => {
      getScoreList({ c_id: thus.classId });
    };
    const openDialog = (row,index) => {
      // thus.rowStudentScore = { ...row };
      // thus.rowStudentScore = row
      thus.rowStudentScore =  JSON.parse(JSON.stringify(row));
      thus.rowIndex = index;
      thus.newScore.student_id = row.id
      thus.dialogVisible = true;
    };
    const scoreUpdate = (row) => {
      if (!row.type) {
        return (row.type = true);
      }
      request.put("/score/update", row).then((res) => {
        if (res.status != 200) {
          return ElMessage.error(res.message);
        }
        ElMessage.success(res.message);
        row.type = false;
      });
    };
    // 计算属性 过滤掉已经有的科目
    let courseListFilter = computed(()=>{
      console.log(thus.courseList);
      console.log(thus.rowStudentScore);
      return thus.courseList.filter(item=>{
       return thus.rowStudentScore.score.filter(e=>{
          return item.id==e.course_id
        }).length>0?false:true
      })
    })
    const addScore = ()=>{
      console.log(thus.newScore);
      const num = Number(thus.newScore.num)
      const {student_id} = thus.newScore
      request.post('/score/add',{...thus.newScore,num}).then(res=>{
        if(res.status!=200){
          return ElMessage.error(res.message)
        }
        ElMessage.success(res.message);
        getScoreList({student_id},true)
        thus.newScore.course_id = null;
        thus.newScore.num = null;
      })
    }
    const scoredelete = (row) => {
      console.log(row);
      request.delete(`/score/delete/${row.student_id}/${row.course_id}`).then(res=>{
        if(res.status!=200) return ElMessage.error(res.message)
        ElMessage.success(res.message)
        getScoreList({student_id:row.student_id},true)
      })
    }
    getClassAndCourseList();
    getScoreList(null);
    const handleSizeChange = (val) => {
      console.log(`${val} items per page`);
      thus.pag.pageSize = val;
    };
    const handleCurrentChange = (val) => {
      console.log(`current page: ${val}`);
      thus.pag.currentPage = val;
    };
        // 计算显示区域
    const handleChangeIndexL = computed(() => {
      return thus.pag.currentPage * thus.pag.pageSize;
    });
    const handleChangeIndexF = computed(() => {
      return (thus.pag.currentPage - 1) * thus.pag.pageSize;
    });
    return {
      Delete,
      ...toRefs(thus),
      type,
      changeClass,
      openDialog,handleChangeIndexL,handleChangeIndexF,scoredelete,
      scoreUpdate,addScore,courseListFilter,handleSizeChange,handleCurrentChange
    };
  },
};
</script>

<style lang="less">
.table {
  margin: 0 10px;
}
.km_table {
  display: flex;
  align-items: center;
  justify-content: center;
  // border: 1px solid #333;
  text-align: center;

  span {
    p {
      padding: 5px 10px;
      border: 1px solid rgba(0, 0, 0, 0.3);
    }
    p:nth-child(1) {
      font-weight: 700;
    }
  }
}
.el-table-fixed-column--right{
  background: rgba(255, 255, 255, 0.3)!important;
  color: #333;
}
.el-form-item__content{
  flex-wrap: nowrap;
}
</style>